package com.xyhy.core.utils.jdk;

import cn.hutool.core.collection.CollUtil;

import java.util.*;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;

public class StreamUtil {

  public static <T, R> List<R> toList(Collection<T> list, Function<T, R> fn) {
    if (CollUtil.isEmpty(list)) return Collections.emptyList();
    return list.stream().map(fn).collect(Collectors.toList());
  }

  public static <T, R> List<R> toDistinctList(Collection<T> list, Function<T, R> fn) {
    if (CollUtil.isEmpty(list)) return Collections.emptyList();
    return list.stream().map(fn).distinct().collect(Collectors.toList());
  }

  public static <T, R> Set<R> toSet(Collection<T> list, Function<T, R> fn) {
    if (CollUtil.isEmpty(list)) return Collections.emptySet();
    return list.stream().map(fn).collect(Collectors.toSet());
  }

  public static <T, K, R> Map<K, R> toMap(Collection<T> list, Function<T, K> keyFn, Function<T, R> valueFn) {
    if (CollUtil.isEmpty(list)) return Collections.emptyMap();
    return list.stream().collect(CollectorUtils.toMap(keyFn, valueFn));
  }

  public static <T, K, R> Map<K, R> toMap(Collection<T> list, Function<T, K> keyFn, Function<T, R> valueFn,
                                          BinaryOperator<R> mergeFunction) {
    if (CollUtil.isEmpty(list)) return Collections.emptyMap();
    return list.stream().collect(CollectorUtils.toMap(keyFn, valueFn, mergeFunction));
  }

}
